package git.soulbgm.utils;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * protostuff序列化工具类
 *
 * @author SoulBGM
 * @date 2024/02/29
 */
public class ProtostuffUtil {

    private static final Map<Class<?>, Schema<?>> CACHED_SCHEMA = new ConcurrentHashMap<>();

    private static <T> Schema<T> getSchema(Class<T> clazz) {
        @SuppressWarnings("unchecked")
        Schema<T> schema = (Schema<T>) CACHED_SCHEMA.get(clazz);
        if (schema == null) {
            schema = RuntimeSchema.createFrom(clazz);
            CACHED_SCHEMA.put(clazz, schema);
        }
        return schema;
    }

    /**
     * 将对象通过protostuff的方式进行序列化得到byte[]
     *
     * @param t 要序列化的对象
     * @return {@link byte[]}
     */
    public static <T> byte[] serializer(T t) {
        Class<T> clazz = (Class<T>) t.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema<T> schema = getSchema(clazz);
            return ProtobufIOUtil.toByteArray(t, schema, buffer);
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        } finally {
            buffer.clear();
        }
    }

    /**
     * 将通过protostuff的方式序列化的byte[] 进行反序列化成实体对象
     *
     * @param data  protostuff的方式序列化的byte[]数据
     * @param clazz 要进行反序列化成实体的Class
     * @return {@link T}
     */
    public static <T> T deserializer(byte[] data, Class<T> clazz) {
        try {
            Schema<T> schema = getSchema(clazz);
            T t = schema.newMessage();
            ProtobufIOUtil.mergeFrom(data, t, schema);
            return t;
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

}
